<template>
	<view class="main">
		<view class="content">
			<template v-for="(item, index) in tableData" :key="index">
				<view class="avatar" @click="handleClick(item)">
					<image class="img" :src="item.cover_url"></image>
				</view>
				<view v-if="(index + 1) % 12 === 0" class="box-id">
					<ad-custom :unit-id="$store.state.configInfo.adIds.nativeAd2"></ad-custom>
				</view>
			</template>

		</view>
		<up-loadmore class="loadmore" :status="hasMore ? 'loading' : 'nomore'" />
		<up-popup :show="show" mode="center" :round="12" :closeable="true" @close="show = false">
			<image class="popup-img" :src="selectSrc" mode="widthFix"></image>
			<view class="popup-btn" @click="handleAvatar(selectSrc)">
				<up-icon v-if="$store.state.configInfo.adEnabled.avatarAdStatus" name="lock" color="#fff" size="24"></up-icon>
				保存图片
			</view>
		</up-popup>
	</view>
</template>

<script>
	import adVideo from '@/utils/adVideo';
	const http = uniCloud.importObject("wallpaper", {
		customUI: true
	})
	
	export default {
		mixins: [adVideo],
		data() {
			return {
				pageNum: 1,
				tableData: [],
				hasMore: true,
				show: false,
				selectSrc: '',
			};
		},
		onLoad() {
			this.getTableData();
		},
		onReachBottom() {
			this.pageNum++
			this.getTableData()
		},
		methods: {
			async getTableData() {
				const res = await http.getAvatarList(this.pageNum)
				if (res.code === 200) {
					if (!res.data.length) {
						this.hasMore = false
					}
					this.tableData = this.tableData.concat(res.data)
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'error'
					})
				}
			},
			handleClick(item) {
				this.selectSrc = item.cover_url
				this.show = true
			},
			handleAvatar(src) {
				const regex = /src=([^&?]+)/;
				const match = src.match(regex);
				// if (match && match[1]) {
				// 	this.handleDownload(match[1]);
				// }
				if (this.$store.state.configInfo.adEnabled.avatarAdStatus) {
					this.handleDownload(match[1]);
				} else {
					this.saveImage(match[1]);
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	.content {
		display: grid;
		gap: 12rpx;
		grid-template-columns: repeat(3, 1fr);
		padding: 32rpx;

		.avatar {
			aspect-ratio: 1 / 1;
			width: 100%;
			overflow: hidden;
		}

		.img {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		.box-id {
			grid-column: 1 / -1;
		}
	}

	.loadmore {
		padding-bottom: 32rpx;
	}

	.popup-img {
		width: 600rpx;
		margin: 96rpx 32rpx 24rpx;
		box-sizing: border-box;
	}

	.popup-btn {
		width: 400rpx;
		padding: 12rpx 0;
		font-size: 38rpx;
		background-image: linear-gradient(to bottom right, #FE73DA, #FF9056);
		border-radius: 999rpx;
		color: #fff;
		position: relative;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
		margin-bottom: 32rpx;
	}
</style>